import {b as browser} from "./browser-polyfill";


interface Tab {
  id: string;
  title: string;
}

export const getTab = async ({title} : {title: string}): Promise<Tab> => {
  let queryOptions;
  if(title) {
    queryOptions = { title: title };
  } else {
    queryOptions = { active: true, lastFocusedWindow: true };
  }
  const [tab] = await browser.tabs.query(queryOptions);
  if(!tab) {
    throw new Error("未查询到对应的标签页！");
  }
  return {id: tab.id, title: tab.title};
};

export const createTab = async ({url}) => {
  await browser.tabs.create({
    url: url,
  });
};

export const reloadTab = async ({title}) => {
  const tab = await getTab({title});
  await browser.tabs.reload(tab.id, { bypassCache: true });
};

export const removeTab = async ({title}) => {
  const tab = await getTab({title});
  await browser.tabs.remove(tab.id);
};

export const switchTab = async ({title}) => {
  const tab = await getTab({title});
  await browser.tabs.update(tab.id, { active: true});
};

export const getEle = async ({selector, title}: {selector: string, title: string}) => {
    const tab = await getTab({title: title});
    const response = await browser.tabs.sendMessage(tab.id, {selector})
    return response;
}

export const getTabs = async (): Promise<Tab[]> => {
  const result: Tab[] = []; 
  const tabs = await browser.tabs.query({});
  for(let tab of tabs) {
    result.push({id: tab.id, title: tab.title});
  } 
  return result;
};